package com.travel.travel_springboot_web.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.travel_springboot_web.entity.GiftRule;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedTypes(List.class)
public class GiftRuleListTypeHandler extends BaseTypeHandler<List<GiftRule>> {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<GiftRule> parameter, JdbcType jdbcType)
            throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (Exception e) {
            throw new SQLException("Error converting gift rules to JSON", e);
        }
    }
    
    @Override
    public List<GiftRule> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseGiftRules(rs.getString(columnName));
    }
    
    @Override
    public List<GiftRule> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseGiftRules(rs.getString(columnIndex));
    }
    
    @Override
    public List<GiftRule> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseGiftRules(cs.getString(columnIndex));
    }
    
    private List<GiftRule> parseGiftRules(String json) throws SQLException {
        try {
            if (json == null || json.isEmpty()) {
                return null;
            }
            return objectMapper.readValue(json, new TypeReference<List<GiftRule>>() {});
        } catch (Exception e) {
            throw new SQLException("Error parsing gift rules JSON", e);
        }
    }
} 